﻿using System;
using System.IO;
using System.Linq;

namespace picomp
{
    public class Transformer
    {
        public Transformer(string filename, string outFolder)
        {
            OutFolder = outFolder;
            Filename = filename;
        }

        public string Filename { get; private set; }
        public string OutFolder { get; private set; }

        private string ToZipFilename()
        {
            return Path.Combine(OutFolder, Path.ChangeExtension(Path.GetFileName(Filename), ".zip"));
        }

        public void Transform()
        {
            var reader = new ZipReader(Filename);
            var writer = new ZipWriter(ToZipFilename());
            var counter = 1;
            var randomId = Utilities.RandString();
            const string FILENAME_TPL = @"{0}_{1:d4}.jpg";

            try
            {
                try
                {
                    var total = reader.CountImageFiles();
                    foreach (var image in reader.ImageFiles().Where(x => x != null))
                    {
                        writer.WriteStream(image, string.Format(FILENAME_TPL, randomId, counter));
                        Console.WriteLine("\t{0}/{1}", counter++, total);
                        if (counter%100 == 0)
                            Utilities.Breathe();
                    }

                    foreach (var otherFile in reader.OtherFiles(randomId).Where(otherFile => otherFile != null))
                    {
                        writer.WriteFile(otherFile);
                        Console.WriteLine(otherFile.Name);
                    }
                }
                catch
                {
                    // Ignore
                    return;
                }
            }
            finally
            {
                writer.Close();
            }

            Utilities.Breathe();
        }
    }
}